package com.flying.test.service;

import com.flying.test.entity.User;
import com.flying.test.repository.UserRepository;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class UserService {
    private final UserRepository repository;

    public UserService(UserRepository repository) {
        this.repository = repository;
    }

    public Optional<User> login(String email, String password) {
        return repository.login(email, password);
    }

    public User createUser(User user) {
        Optional<User> userOptional = repository.findByEmail(user.getEmail());
        if (userOptional.isPresent()) {
            throw new RuntimeException("User with email " + user.getEmail() + " already exists");
        }
        return repository.save(user);
    }

    public User updateUser(User user) {
        return repository.save(user);
    }

    public List<User> findAllUsers() {
        return repository.findAll();
    }

    public Optional<User> findUserById(Long id) {
        return repository.findById(id);
    }

    public void deleteUserById(Long id) {
        repository.deleteById(id);
    }
}